package com.gitee.wsl.coroutines.strategy.lazy

import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async

/**
 * An imitator of [Deferred] which holds a suspended function block and dispatcher
 */
class LazyDeferred<out T>(
    val dispatcher: CoroutineDispatcher,
    val block: suspend CoroutineScope.() -> T
) {
    private var deferred: Deferred<T>? = null

    fun start(scope: CoroutineScope) {
        if (deferred == null) deferred = scope.async(dispatcher, block = block)
    }

    suspend fun await(): T = deferred?.await() ?: error("Coroutine not started")
}